package example.dao.openjpa;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import example.dao.IAccountDao;
import example.dao.IFactoryDAO;

public class FactoryJPADao implements IFactoryDAO {
	
	private EntityManagerFactory emf;
	
	EntityManager em;
	
	private AccountJPADao accountDao;
	
	private FactoryJPADao(){
		init();
	}
	
	public void init() {
		System.out.println("FactoryDao created..!");
		emf = Persistence.createEntityManagerFactory("DataLayer");
		em = emf.createEntityManager(); 
	}
	   
	public void destroy() {
		System.out.println("FactoryDao destroyed..!");
		em.close();
		emf.close();
	}
	
	/* (non-Javadoc)
	 * @see example.dao.openjpa.FactoryDAO#getAccountDao()
	 */
	public IAccountDao getAccountDao() {
		if (accountDao==null) {
			accountDao = new AccountJPADao();
			accountDao.setEntityManager(em);
			return accountDao;
		}
		else 
			return accountDao;
	}
	
	/* (non-Javadoc)
	 * @see example.dao.openjpa.FactoryDAO#startTrasaction()
	 */
	public void startTrasaction() {
		System.out.println("FactoryJPADao start transaction");
		em.getTransaction().begin();
	}
	
	/* (non-Javadoc)
	 * @see example.dao.openjpa.FactoryDAO#commitTransaction()
	 */
	public void commitTransaction() {
		System.out.println("FactoryJPADao commit transaction");
		em.getTransaction().commit();
		em.clear();		
	}
	
	/* (non-Javadoc)
	 * @see example.dao.openjpa.FactoryDAO#roolbackTransaction()
	 */
	public void roolbackTransaction() {
		System.out.println("FactoryJPADao rollback transaction");
		em.clear();
		em.flush();
		em.getTransaction().rollback();
	}
	
	public String toString() {
		return "FactoryJPADao";
	}
	

}
